<?php

namespace AuthDoctrine\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

use AuthDoctrine\Form\LoginForm;

class IndexController extends AbstractActionController
{
   
    public function indexAction()
    {
        $users = $this->getEntityManager()->getRepository('AuthDoctrine\Entity\Users')->findAll();
        
        $message = $this->params()->fromQuery('message' , 'fo');
        
        return new ViewModel(array(
            'message' => $message,
			'users'	=> $users,
        ));
    }
    
    public function loginAction()
    {
        if($this->identity())
        {
            return $this->redirect()->toRoute('authdoctrine/default' , array('controller' => 'Index' , 'action' => 'index'));
        }
        $form = new LoginForm();
        $message = null;
        
        $request = $this->getRequest();
        if($request->isPost())
        {
            $form->setData($request->getPost());
            if($form->isValid())
            {
                $data = $form->getData();
                
                $authService = $this->getServiceLocator()->get('Zend\Authentication\AuthenticationService');
                $adapter = $authService->getAdapter();
                $adapter->setIdentityValue($data['username']);
                $adapter->setCredentialValue($data['password']);
                $authResult = $authService->authenticate();      
                //var_dump($authResult);
                if ($authResult->isValid()) { 
                    $identity = $authResult->getIdentity();
					$authService->getStorage()->write($identity);      
					$time = 1209600; //-					
					if ($data['rememberme']) {
						$sessionManager = new \Zend\Session\SessionManager();
						$sessionManager->rememberMe($time);
					}
                }
                foreach ($authResult->getMessages() as $message) {
					$messages[] = $message . "\n"; 
				}                      
            }            
        }
        
        return new ViewModel(array(
            'error' => 'Your authentication credentials are not valid',
			'form'	=> $form,
			'messages' => $messages
        ));
    }

    protected $sm = null;
    public function getEntityManager()
	{
		if (null === $this->em) {
			$this->em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
		}
		return $this->em;
	}
    
}

